package org.soenea.doitall.domain.command;

import org.dsrg.soenea.domain.command.CommandError;
import org.dsrg.soenea.domain.command.CommandException;
import org.dsrg.soenea.domain.command.impl.Command;
import org.dsrg.soenea.domain.helper.Helper;
import org.dsrg.soenea.domain.mapper.DomainObjectNotFoundException;
import org.dsrg.soenea.service.SingleAppUniqueIdFactory;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.domain.command.exception.*;
import org.soenea.doitall.domain.model.group.*;
import org.soenea.doitall.domain.model.group.mapper.*;
import org.soenea.doitall.domain.model.invite.*;
import org.soenea.doitall.domain.model.user.*;
import org.soenea.doitall.domain.model.user.mapper.*;

public class InviteMemberCommand extends Command {
	public InviteMemberCommand(Helper helper) {
		super(helper);
	}

	@Override
	public void setUp() throws CommandException {
		// TODO Auto-generated method stub		
	}

	@Override
	public void process() throws CommandException {
		Group group;
		try {
			long userID = (Long)helper.getSessionAttribute("UserID");
			long groupID = (Long)helper.getSessionAttribute("GroupID");

			if (groupID == 0)
				throw new CommandException("You must be a part of a group to invite members.");

			String username = helper.getString("username");
			group = GroupInputMapper.find(groupID);

			User user = UserInputMapper.find(username);

			if (user.getGroupID() != 0)
				throw new MemberAlreadyInGroupException();

			long inviteID = SingleAppUniqueIdFactory.getMaxId("invite", "inviteID");

			Invite newInvite = new Invite(inviteID, 1, new UserProxy(userID), user, group, 0);
			UoW.getCurrent().registerNew(newInvite);
			UoW.getCurrent().commit();
		} catch (DomainObjectNotFoundException e) {
			throw new MemberNotFoundException();			   
        } catch (CommandException e) {
        	throw e;
        } catch (Exception e) {
           throw new CommandException(e);
        }
	}

	@Override
	public void tearDown() throws CommandError {
		// TODO Auto-generated method stub
	}
}
